{
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
}

unit SecureRandom;

interface

uses
  Classes, SysUtils;

procedure GenerateSecureRandom(out Buffer; BufferSize: Integer);
function SecureRandomInteger(Range: Integer): Integer;
function SecureRandomFloat: Extended;

implementation

function RtlGenRandom(out RandomBuffer; RandomBufferLength: Cardinal): LongBool; stdcall;
  external 'advapi32.dll' name 'SystemFunction036';

procedure GenerateSecureRandom(out Buffer; BufferSize: Integer);
begin
  Assert( BufferSize >= 0 );
  if BufferSize > 0 then
  begin
    if not RtlGenRandom(Buffer, BufferSize) then
      raise Exception.Create('RtlGenRandom failed.');
  end;
end;

function SecureRandomInteger(Range: Integer): Integer;
var
  n: Integer;
begin
  if Range >= 2 then
  begin
    repeat
      GenerateSecureRandom(n, SizeOf(n));
      n := n and MaxInt;
      Result := n mod Range;
    until n - Result <= MaxInt - Range + 1;
  end
  else
    Result := 0;
end;

function SecureRandomFloat: Extended;
var
  n: Cardinal;
begin
  GenerateSecureRandom(n, SizeOf(n));
  Result := n / $100000000;
end;

end.

